<?php

namespace Yjius\EasyappYii\modules\ucenter\controllers;

use Yjius\EasyappYii\modules\ucenter\models\TokenModel;
use Yjius\EasyappYii\modules\ucenter\models\UserModel;
use Yjius\EasyappYii\modules\ucenter\services\UserService;

class UserController extends UcenterController
{

    protected $noNeedLoginRoute = ['ucenter/user/register','ucenter/user/login'];

    public function actionRegister()
    {
        $username = $this->loadParam("username", "");
        $mobile = $this->loadParam("mobile", "");
        $password = $this->loadParam("password", "");
        if (empty($mobile)) {
            $this->error("手机号不能为空");
        }
        if (empty($username)) {
            $this->error("用户名不能为空");
        }
        if (empty($password)) {
            $this->error("密码不能为空");
        }
        //当前用户已存在
        $userData = UserModel::getOne(['username' => $username]);
        if (!empty($userData)) {
            $this->error("用户信息已存在");
        }
        $userRegData = [
            "username" => $username,
            "create_date" => date("Y-m-d H:i:s"),
            "mobile" => $mobile,
            "salt" => UserService::generateSalt(),
        ];
        $userRegData["password"] = UserService::generatePassword($password, $userRegData['salt']);

        $userRegData["id"] = UserModel::saveDataNoExistAdd($userRegData);

        $jwt = UserService::generateToken($userRegData);

        $data = ["token" => $jwt];

        $this->success($data, "注册成功");

    }

    public function actionLogin()
    {
        $username = $this->loadParam("username", "");
        $password = $this->loadParam("password", "");
        if (empty($username) || empty($password)) {
            $this->error("用户名或密码不能为空");
        }
        // ... 进行用户名密码验证
        $userData = UserModel::getOne(['username' => $username]);
        if (empty($userData)) {
            $this->error("用户信息不存在");
        }
        $password = UserService::generatePassword($password, $userData['salt']);
        if ($password != $userData['password']) {
            $this->error("用户名或密码错误");
        }
        // ... 验证通过后，生成token，并返回给客户端

        $jwt = UserService::generateToken($userData);

        $data = ["token" => $jwt];

        $this->success($data, "登录成功");
    }


    public function actionLogout()
    {
        TokenModel::deleteAll(['user_id' => $this->getLoginUser()['id']]);
        $this->success([], "退出成功");
    }


}